import { createSlice } from "@reduxjs/toolkit";
import { removeToken } from "@/utils";
import {setToken as _setToken, getToken} from '@/utils'
import {getProfileAPI,loginAPI} from '@/apis/user'


const userStore = createSlice({
    name: 'user',
    // 数据状态
    initialState: {
        token: getToken() || '',
        userInfo:{},
    },
    // 同步修改方法
    reducers: {
        setToken (state, action) {
            state.token = action.payload;
            _setToken(action.payload);
        },
        setUserInfo(state, action) {
            state.userInfo = action.payload
        },
        clearUserInfo(state) {
            // 清空redux信息
            state.userInfo = {}
            state.token = ''
            // 清空本地token
            removeToken('token_key')
        }

    }
});

// 解构出actionCreate
const { setToken,setUserInfo,clearUserInfo } = userStore.actions;
// 获取reducer函数
const userReducer = userStore.reducer;


// 异步方法 完成登录获取token
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        const res = await loginAPI(loginForm);
        dispatch(setToken(res.data.data.token));
    };
};

// 异步方法,获取个人信息
const fetchUserInfo = () => {
    return async (dispatch) => {
      const res = await getProfileAPI()
      console.log(res.data)
      dispatch(setUserInfo(res.data))
    }
  }

export { setToken, fetchLogin,fetchUserInfo,clearUserInfo };
// 导出reducer
export default userReducer;